import React, { useEffect, useState } from "react";
import ProTypes from "prop-types";
import "./FileSearch.css";
import useInputFocus from "../hooks/useInputFocus";
import useKeyPress from "../hooks/useKeyPress";
import useIpcRenderer from "../hooks/useIpcRenderer";

const FileSearch = ({ title, onFileSearch }) => {
    const [inputActive, setInputActive] = useState(false);
    const [value, setValue] = useState("");
    // 按下enter
    const enterPressed = useKeyPress(13);
    // 按下esc
    const escPressed = useKeyPress(27);
    const closeSearch = () => {
        // 取消input显示
        setInputActive(false);
        // 清空已输入的input value
        setValue("");
        // 清空搜索框
        onFileSearch("");
    };

    // 监听键盘事件,这里必须加第二个参数，否则报错
    useEffect(() => {
        if (enterPressed && inputActive) {
            onFileSearch(value);
        }
        if (escPressed && inputActive) {
            closeSearch();
        }
    }, [enterPressed, escPressed]); //只有数组里的参数状态改变时才执行，等于空的话，只有销毁时才执行
    // input聚焦
    const inputRef = useInputFocus(inputActive);

    useIpcRenderer({
        "search-file": () => {
            setInputActive(true);
        },
    });

    return (
        <div className="alert alert-primary pt-1 pb-1 mb-0 rounded-0">
            {!inputActive && (
                <div className="d-flex justify-content-between align-items-center row">
                    <div className="col-10 search-height">{title}</div>
                    <button
                        type="button"
                        className="icon-button col-2"
                        onClick={() => {
                            setInputActive(true);
                        }}
                    >
                        <i className="bi bi-search"></i>
                    </button>
                </div>
            )}
            {inputActive && (
                <div className="row">
                    {/* 这里的 col-8 必须写在外层div上，如果写在input上，就会和form-control样式冲突 */}
                    <div className="col-8">
                        <input
                            ref={inputRef}
                            className="form-control search-height"
                            value={value}
                            onChange={(e) => {
                                setValue(e.target.value);
                            }}
                        />
                    </div>
                    <button type="button" className="icon-button col-4" onClick={closeSearch}>
                        <i className="bi bi-x-lg"></i>
                    </button>
                </div>
            )}
        </div>
    );
};

// 使用 ProTypes 校验
FileSearch.propTypes = {
    title: ProTypes.string,
    onFileSearch: ProTypes.func.isRequired,
};

// 默认值
FileSearch.defaultProps = {
    title: "我的云文档",
};

export default FileSearch;
